/*
    1 直接复制语句 1 <var> <expr>
    2 间接赋值语句 2 <var> <expr> 动态求值
*/
#include <iostream> 
#include <sstream>
#include <algorithm>
#include <map>
#include <string>
#include <vector>
using namespace std;
template <typename T>
inline void read(T& x)
{
    int c=getchar(), f=1; x=0;
    while(c<'0'||'9'<c) {if(c=='-') f=-1; c=getchar();}
    while('0'<=c&&c<='9') 
        x=(x<<3)+(x<<1)+c-'0', c=getchar();
    x*=f;
}

inline void write(long long x)
{
    if(x>=10) write(x/10);
    putchar(x%10+'0');
}
#define DEBUG
using ll=long long;
const int N=1e4+10, M=1e6+10;
int n;
map<string, bool> dyna;
map<string, string> staticmp;
map<string, vector<string>> dynamp;

int op;
string var;
vector<string> expr;
void init()
{
    read(n);
}

inline void readop()
{
    op=0; var.clear(); expr.clear();
    string line, word;
    getline(cin, line);
    istringstream ssin(line);
    ssin >> op;
    // op-='0';
    ssin >> var;
    while(ssin>>word)
        expr.push_back(word);
}

string workop2(string opstr) //动态拼接
{
    if(!dyna[opstr]) return "";
    string ans;
    for(auto str:dynamp[opstr])
    {
        if(str[0]=='$')
        {
            str.erase(0, 1);
            if(dyna[str]) ans+=workop2(str); //需要动态处理
            else ans+=staticmp[str]; //静态变量
        }
        else ans+=str;
    }
    // cout << "2" << " " << opstr << ":" << ans << endl;
    return ans;

}

void op1()
{
    string ans;
    for(auto str:expr)
    {
        if(str[0]=='$')
        {
            str.erase(0, 1);
            if(dyna[str]) ans+=workop2(str); //需要动态处理
            else ans+=staticmp[str]; //静态变量
        }
        else ans+=str;
    }
    staticmp[var]=ans;
    // cout << op << " " << var << ":" << staticmp[var] << endl;
}

void op2()
{
    dyna[var]=1;
    dynamp[var]=expr;
}

void op3()
{
    if(dyna[var]) 
        write(workop2(var).size()); 
    else write(staticmp[var].size()); 
    puts("");
}

void solve()
{
    init();
    while(n--)
    {
        readop();
        // cout << "op:" << op << " var:" << var << endl;
        if(op==1)
            op1();
        else if(op==2)
            op2();
        else if(op==3)
            op3();
    }
}

signed main()
{
    #ifdef DEBUG
        freopen("../in.txt", "r", stdin);
        freopen("../out.txt", "w", stdout);
    #endif

    int T=1; //scanf("%d", &T);
    while(T--) 
    {
        solve();
    }
    return 0;
}